/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    bool isValidBST(TreeNode *root)
    {
        int num = 0;
        bool first = true;
        return inorderTraversal(root, num, first);
    }

    bool inorderTraversal(TreeNode *tree, int &lastNum, bool &isFirst)
    {
        if (tree == nullptr)
        {
            return true;
        }
        if (!inorderTraversal(tree->left, lastNum, isFirst))
        {
            return false;
        }
        if (isFirst)
        {
            lastNum = tree->val;
            isFirst = false;
        }
        else if (tree->val <= lastNum)
        {
            return false;
        }
        else
        {
            lastNum = tree->val;
        }
        if (!inorderTraversal(tree->right, lastNum, isFirst))
        {
            return false;
        }
        return true;
    }
};